#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define INITIAL_CAPACITY 10
// 这里假设 StudentManager 结构体和相关函数已经在 c.c 中定义
typedef struct {
    char **name;
    int count;
    int capacity;
}StudentManager;

// 函数声明
// 初始化函数
void initStudentManager(StudentManager *manager){
    manager -> name = (char **)malloc(INITIAL_CAPACITY * sizeof(char *));// 分配初始容量
    manager -> count = 0;// 当前学生数量
    manager -> capacity = INITIAL_CAPACITY;// 数组最大容量
}
// 扩容函数,capacity容量翻倍，扩容*name
void expendCapacity(StudentManager *manager){
    int new_capacity = manager -> capacity * 2;// 新容量
    char **new_name = (char **)realloc(manager -> name, new_capacity * sizeof(char *));// 重新分配内存
    if(new_name == NULL){
        printf("Memory allocation failed\n");// 内存分配失败
        return;
    }
    manager -> name = new_name;// 更新指针
    manager -> capacity = new_capacity;// 更新容量

}
// 添加学生姓名的函数
void addStudent(StudentManager *manager, const char *name){
    // 检查是否需要扩容
    if(manager -> count >= manager -> capacity){
        expendCapacity(manager);
    }
    // 为新姓名分配内存（长度为字符串长度 + 1，用于存放结束符 '\0'）
    manager -> name[manager -> count] = (char *)malloc(strlen(name) + 1);
    // 复制字符串到分配的内存中
    strcpy(manager -> name[manager -> count], name);
    // 更新学生数量
    manager -> count++;
}
// 释放内存的函数，避免内存泄漏
void freeStudentManager(StudentManager *manager){
    // 先释放每个字符串的内存
    for(int i = 0; i < manager -> count; i++){
        free(manager -> name[i]);
    }
    // 再释放存放指针的数组
    free(manager -> name);
    manager -> name = NULL;
    manager -> count = 0;
    manager -> capacity = 0;
}
int main(){
    StudentManager manager;
    initStudentManager(&manager);
    
    // 添加一些学生姓名
    addStudent(&manager, "Alice");
    addStudent(&manager, "Bob");
    addStudent(&manager, "Charlie");
    
    // 打印学生姓名
    for(int i = 0; i < manager.count; i++){
        printf("%s\n", manager.name[i]);
    }
    // 添加更多学生姓名以测试扩容
    addStudent(&manager, "World");
    addStudent(&manager, "Test");
    addStudent(&manager, "Data");
    addStudent(&manager, "Structure");
    addStudent(&manager, "Example");
    addStudent(&manager, "Programming");
    addStudent(&manager, "Language");
    addStudent(&manager, "C");
    
    // 打印学生姓名
    for (int i = 0; i < manager.count; i++) {
        printf("%s\n", manager.name[i]);
    }

    // 释放内存
    freeStudentManager(&manager);

    return 0;
}